package com.df.barcodescaning.ui;

import android.app.Activity;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.df.barcodescaning.MyApplication;
import com.df.barcodescaning.R;
import com.df.barcodescaning.bean.UserData;
import com.df.barcodescaning.bean.UserGroup;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by G on 2018/5/31.
 */

public class UserManageAdapter  extends RecyclerView.Adapter<UserManageAdapter.Holder> {

    Context context;
    private UserGroup userGroup;
    private Map<String, UserData> userMap;
    private List<String> userList;

    public UserManageAdapter(Context context, UserGroup userGroup) {
        this.context = context;
        this.userGroup = userGroup;
        userMap = userGroup.getValues();
        userList = new ArrayList<>();
        for (String key : userMap.keySet()) {
            userList.add(key);
        }
    }

    @Override
    public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
        View root = ((Activity)context).getLayoutInflater().inflate(R.layout.item_user_details, null);
        return new Holder(root);
    }

    @Override
    public void onBindViewHolder(Holder holder, final int position) {
        holder.tv.setText(userList.get(position));
        holder.delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                delUser(position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return userList.size();
    }

    public void addUser(String user) {
        userList.add(user);
        notifyItemInserted(userList.size() - 1);//通知演示插入动画
        notifyItemRangeChanged(userList.size()-1,1);//通知数据与界面重新绑定
    }

    public void delUser(int position) {
        String userName = userList.get(position);
        if (userMap.get(userName).isManager()) {
            Toast.makeText(context, "管理员账户不可修改!", Toast.LENGTH_LONG).show();
            return;
        }
        userMap.remove(userList.get(position));
        userGroup.setValues(userMap);
        MyApplication.getInstance().saveRegistedUser(userGroup);
        userList.remove(position);
        notifyItemRemoved(position);
        notifyItemRangeChanged(position, userList.size()-position);
    }

    class Holder extends RecyclerView.ViewHolder {
        private TextView tv;
        private View delete;
        Holder(View view){
            super(view);
            tv = view.findViewById(R.id.tv_record_details_tittle);
            delete = itemView.findViewById(R.id.delete);
        }
    }
}
